﻿
namespace LS.Nc6.Application.System
{
    /// <summary>
    /// 提供角色管理服务
    /// </summary>

    public class SysRoleService : BaseService<SysRoleEntity>, ISysRoleService, ITransient
    {
        public async Task<int> InsertRoleMenu(SysRoleEntity model, List<SysRoleMenuEntity> listModel)
        {
            try
            {
                DbContext.Instance.BeginTran();
                await DbContext.Instance.Insertable(model).ExecuteCommandAsync();
                if (listModel != null && listModel.Count > 0)
                {
                    await DbContext.Instance.Insertable(listModel).ExecuteCommandAsync();
                }
                DbContext.Instance.CommitTran();
                return 1;
            }
            catch (Exception)
            {
                DbContext.Instance.RollbackTran();
                throw;
            }
        }

        public async Task<int> UpdateRoleMenu(SysRoleEntity model, List<SysRoleMenuEntity> listModel)
        {

            try
            {
                DbContext.Instance.BeginTran();
                await DbContext.Instance.Updateable(model).ExecuteCommandAsync();
                await DbContext.Instance.Deleteable<SysRoleMenuEntity>().Where(a=>a.RoleCode ==model.RoleCode).ExecuteCommandAsync();

                if (listModel != null && listModel.Count > 0)
                {
                    await DbContext.Instance.Insertable(listModel).ExecuteCommandAsync();
                }
                DbContext.Instance.CommitTran();
                return 1;
            }
            catch (Exception)
            {
                DbContext.Instance.RollbackTran();
                throw;
            }
        }

        public async Task<bool> ExistsRoleCode(string id, string roleCode)
        {
            return await DbContext.Instance.Queryable<SysRoleEntity>().WhereIF(!string.IsNullOrEmpty(id), a => a.Id != id.ParseToLong()).WhereIF(!string.IsNullOrEmpty(roleCode), a => a.RoleCode == roleCode)
                .CountAsync() > 0;
          
        }

        public async Task<List<SysRoleMenuEntity>> RoleMenuList(string roleCode)
        {
            return await DbContext.Instance.Queryable<SysRoleMenuEntity>().Where(a => a.RoleCode == roleCode).ToListAsync();

        }
    }
}
